<template>
	<!-- #ifdef APP-NVUE -->
	<view class="yb-flex" :id="customIdSync" :class="customClassSync" :style="customStyleSync" @[bindAppear]="onAppear" @[bindDisappear]="onDisappear">
	<!-- #endif -->
	<!-- #ifndef APP-NVUE -->
	<view class="yb-flex" :id="customIdSync" :class="customClassSync" :style="customStyleSync">
	<!-- #endif -->
		<view class="yb-appear yb-flex yb-flex-1" style="min-height: 1px;">
			<template v-if="isShow">
				<slot></slot>
			</template>
		</view>
	</view>
</template>

<script>
	import ComponentMixin from '../../js_sdk/componentMixin.js'
	export default {
		mixins: [ComponentMixin],
		props: {
			target: {
				type: String,
				default: 'viewport'
			},
			disabled: {
				type: Boolean,
				default: false
			}
		},
		computed: {
			bindAppear () {
				return this.disabled ? 'unbindAppear' : 'appear'
			},
			bindDisappear () {
				return this.disabled ? 'unbindDisappear' : 'disappear'
			}
		},
		data () {
			return {
				appear: false,
				isShow: false
			}
		},
		beforeDestroy() {
			// #ifndef APP-NVUE
				this.unbindObserver()
			// #endif
		},
		mounted() {
			this.$nextTick(function() {
				if ( this.disabled ) {
					this.isShow = true
				} else {
					// #ifndef APP-NVUE
					setTimeout(() => {
						this.bindObserver()
						this.isShow = true
					}, 100)
					// #endif
					// #ifdef APP-NVUE
					this.isShow = true
					// #endif
				}
			})
		},
		methods: {
			onAppear () {
				if ( this.disabled ) {
					return
				}
				this.appear = true
				this.$emit('appear')
			},
			onDisappear () {
				if ( this.disabled ) {
					return
				}
				this.appear = false
				this.$emit('disappear')
			},
			bindObserver () {
				this.IntersectionObserver = uni.createIntersectionObserver(this, {
					thresholds: [0, 0.25]
				})
				if ( this.target == 'viewport' ) {
					this.IntersectionObserver.relativeToViewport().observe('.yb-appear', res => {
						if (res.intersectionRatio > 0 && !this.appear) {
							this.onAppear()
						} else if (!res.intersectionRatio > 0 && this.appear) {
							this.onDisappear()
						}
					})
				} else {
					this.IntersectionObserver.relativeTo(this.target).observe('.yb-appear', res => {
						if (res.intersectionRatio > 0 && !this.appear) {
							this.onAppear()
						} else if (!res.intersectionRatio > 0 && this.appear) {
							this.onDisappear()
						}
					})
				}
			},
			unbindObserver () {
				if ( this.IntersectionObserver) {
					this.IntersectionObserver ? this.IntersectionObserver.disconnect() : null
					this.IntersectionObserver = null
				}
			}
		},
		watch: {
			disabled (newVal) {
				if ( newVal ) {
					this.$nextTick(function () {
						this.unbindObserver()
					})
				} else {
					this.$nextTick(function () {
						this.bindObserver()
					})
				}
			}
		}
	}
</script>

<style>
</style>